/***
 * @Author: liujunliang
 * @Date: 2021-12-10 15:38:35
 * @LastEditTime: 2021-12-10 17:44:11
 * @LastEditors: user
 * @Description:
 * @FilePath: /threadTcpServer/src/tcpserver.cpp
 * @你也总是天亮了才睡!
 */
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include "tcpserver.h"
TcpServer::TcpServer(): port_(7777), ip_("0"), backlog_(10) { }
TcpServer::TcpServer(const int port, const char* ip, const int backlog):
    port_(port), ip_(ip), backlog_(backlog)
{ }
int TcpServer::TcpInit()
{
    int listenfd, ret;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == listenfd) {
        perror("socket:");
        return -1;
    }
    int opt = 1;
    ret     = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if(-1 == ret) {
        perror("setsockopt");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(port_);
    addr.sin_addr.s_addr = inet_addr(ip_);

    ret = bind(listenfd, (struct sockaddr*)&addr, sizeof(addr));
    if(-1 == ret) {
        perror("bind:");
        return -1;
    }
    printf("bind success\n");
    ret = listen(listenfd, backlog_);
    if(-1 == ret) {
        perror("listen");
        return -1;
    }
    printf("listen success\n");
    return listenfd;
}
int TcpServer::TcpAceept(int listenfd)
{
    int                aceeptfd, ret;
    struct sockaddr_in addr;
    socklen_t          addrlen = sizeof(addr);
    ret = accept(listenfd, (struct sockaddr*)&addr, &addrlen);
    {
        if(-1 == ret) {
            perror("accept");
            return -1;
        }
    }
    printf("accept success!\n ip :%s, port:%d\n", inet_ntoa(addr.sin_addr),
        addr.sin_port);
    return aceeptfd;
}